package com.example.spring.exercise.config;

import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ExpiryPolicyBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;

/**
 * @author : zhayh
 * @date : 2021-5-3 14:35
 * @description :
 */

@Configuration
@EnableCaching
public class EhCacheConfig {
    public EhCacheConfig() {
        // 创建缓存管理器
        CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(true);
        // 创建名为system的缓存
        cacheManager.createCache("system", CacheConfigurationBuilder.newCacheConfigurationBuilder(
                String.class,  // 缓存的key类型： 字符串
                Object.class,  // 缓存的value类型： 对象
                ResourcePoolsBuilder.heap(20))  // 堆内内存缓存的对象个数： 20
                .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofHours(1))));  // 设置回收时间： 1小时
    }
}
